<template>
  <div class="dailyTask" v-title data-title="项目任务单新增页面">
    <home-nav :userData="userinfo"></home-nav>
    <div class="navigator">
      <div class="baseinfo" ref="imageWrapper">
        <div style="display: flex">
          <span style="margin: 0px auto 30px auto; font-weight: bold; font-size: 20px">新增项目任务单</span>
          <div>
            <span style="color: #31a0e1" v-show="id" @click="openHistory">操作日志</span>
            <span
              style="color: #31a0e1"
              v-if="form.processInstanceId && form.processInstanceId !== '' && form.processStatus != 1"
              @click="openProcessHistory"
            >
              | 审批日志</span
            >
          </div>
        </div>
        <a-form-model class="hte-form-model" ref="ruleForm" :model="form" :rules="rules">
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-model-item label="任务单编号" prop="taskNo">
                <a-input v-model="form.taskNo" disabled placeholder="系统自动生成" />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item ref="taskName" label="任务单名称" prop="taskName">
                <a-input
                  v-model="form.taskName"
                  @blur="
                    () => {
                      $refs.taskName.onFieldBlur()
                    }
                  "
                  placeholder="请输入任务单名称"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="项目信息" prop="projectNo">
                <a-input
                  v-model="projectNoAndName"
                  placeholder="点击选择项目"
                  @click="associated.visible = true"
                  :disabled="kpi.data.length > 0 || form.createType == 1"
                  readOnly
                />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24" v-if="form.taskType != '30'">
            <a-col :span="8">
              <a-form-model-item label="项目节点" prop="timeNodeCode">
                <a-select
                  v-model="form.timeNodeCode"
                  placeholder="请选择未报工的项目节点"
                  :options="timeNodeCodeOptions"
                  @change="timeNodeCodeChange"
                  notFoundContent="请先选择项目"
                  :disabled="kpi.data.length > 0 || form.createType == 1"
                >
                  <a-icon slot="suffixIcon" type="plus" />
                </a-select>
              </a-form-model-item>
            </a-col>

            <a-col :span="8" v-if="form.projectNo != ''">
              <a-form-model-item label="创建人" prop="createUserName">
                <a-input v-model="form.createUserName" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :span="8" v-if="form.projectNo != ''">
              <a-form-model-item label="创建时间" prop="createDate">
                <a-input :value="form.createDate ? timeFormat(form.createDate) : nowDate" disabled />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType != '30'">
            <a-col :span="8" v-if="form.projectNo != ''">
              <a-form-model-item label="主导经营体" prop="mainDeptName">
                <a-input v-model="form.mainDeptName" disabled />
              </a-form-model-item>
            </a-col>

            <a-col :span="8" v-if="form.timeNodeCode">
              <a-form-model-item ref="startDate" label="节点开始时间" prop="startDate">
                <a-input :value="timeFormat(form.startDate)" disabled v-if="!startTimeFlag" />
                <a-date-picker
                  v-model="form.startDate"
                  placeholder="请输入任务开始时间"
                  :allowClear="true"
                  @change="
                    (date, dateString) => {
                      dateSelect(date, dateString, 1)
                    }
                  "
                  v-if="startTimeFlag"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8" v-if="form.timeNodeCode">
              <a-form-model-item ref="endDate" label="节点完成时间" prop="endDate">
                <!-- {{ timeFormat(form.endDate) }} -->
                <a-input :value="timeFormat(form.endDate)" disabled />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24" v-if="form.taskType == '30'">
            <a-col :span="8">
              <a-form-model-item label="项目节点" prop="timeNodeCode">
                <a-select
                  v-model="form.timeNodeCode"
                  placeholder="请选择未报工的项目节点"
                  :options="timeNodeCodeOptions"
                  @change="timeNodeCodeChange"
                  notFoundContent="请先选择项目"
                  :disabled="kpi.data.length > 0"
                >
                  <a-icon slot="suffixIcon" type="plus" />
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8" v-if="form.projectNo != ''">
              <a-form-model-item ref="productSystem" label="产品系统" prop="productSystem">
                <a-cascader
                  v-model="casModel"
                  :options="casProductSystemOptions"
                  :load-data="casLoadData"
                  placeholder="请选择产品系统"
                  change-on-select
                  @change="casProductSystemOnChange"
                  class="headcas"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8" v-if="form.projectNo != ''">
              <a-form-model-item ref="handlerName" label="迭代负责人" prop="handlerName">
                <a-select
                  show-search
                  :value="form.handlerName"
                  placeholder="输入账号或者名称查找用户"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                  @search="fetchHandleUser"
                  @change="fetchHandleChange"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="(d, index) in userHandleData" :key="index" :value="d.username">
                    {{ d.realname }}({{ d.username }})
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == '30'">
            <a-col :span="8" v-if="form.projectNo != ''">
              <a-form-model-item label="创建人" prop="createUserName">
                <a-input v-model="form.createUserName" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :span="8" v-if="form.projectNo != ''">
              <a-form-model-item label="创建时间" prop="createDate">
                <a-input :defaultValue="form.createDate ? timeFormat(form.createDate) : nowDate" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :span="8" v-if="form.projectNo != ''">
              <a-form-model-item label="主导经营体" prop="mainDeptName">
                <a-input v-model="form.mainDeptName" disabled />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == '30'">
            <a-col :span="8" v-if="form.timeNodeCode">
              <a-form-model-item ref="startDate" label="节点开始时间" prop="startDate">
                <a-date-picker
                  v-model="form.startDate"
                  placeholder="请输入任务开始时间"
                  :allowClear="true"
                  @change="
                    (date, dateString) => {
                      dateSelect(date, dateString, 1)
                    }
                  "
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8" v-if="form.timeNodeCode">
              <a-form-model-item ref="endDate" label="节点完成时间" prop="endDate">
                <!-- <a-input :value="timeFormat(form.endDate)" disabled/> -->
                <a-date-picker
                  v-model="form.endDate"
                  placeholder="任务计划完成时间"
                  :allowClear="true"
                  :disabled-date="disabledEndDate"
                  @change="
                    (date, dateString) => {
                      dateSelect(date, dateString, 2)
                    }
                  "
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8" v-if="form.projectNo != ''">
              <a-form-model-item ref="versionNo" label="版本号" prop="versionNo">
                <a-input
                  v-model="form.versionNo"
                  placeholder="格式：v1.0.0 || V1.0.0 "
                  @blur="
                    () => {
                      $refs.versionNo.onFieldBlur()
                    }
                  "
                />
              </a-form-model-item>
              <span style="color: red" v-show="versionTip">当前版本号前5(参考)： {{ versionTip }}</span>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == '30'">
            <a-col :span="8">
              <a-form-model-item ref="businessConfirm" label="需要审批确认" prop="businessConfirm">
                <a-tooltip>
                  <template slot="title">
                    <span
                      >选择是则需要上传《需求规格说明书》提交给业务负责人确认审核，按上线需要提测，可不提测。确认任务单后将无法更改</span
                    >
                  </template>
                  <a-radio-group
                    v-model="form.businessConfirm"
                    v-show="!(form.status > 1)"
                    :disabled="form.status > 1 || form.processStatus == 1 || form.processStatus == 2"
                    @change="radioChange"
                  >
                    <a-radio value="1">是</a-radio>
                    <a-radio value="0">否</a-radio>
                  </a-radio-group>
                  <a-input :value="form.businessConfirm == '1' ? '是' : '否'" disabled v-show="form.status > 1" />
                </a-tooltip>
              </a-form-model-item>
            </a-col>
            <a-col :span="8" v-if="form.id">
              <a-form-model-item ref="testUserName" label="测试员" prop="testUserName">
                <a-select
                  show-search
                  :value="form.testUserName"
                  placeholder="测试员"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                  @search="fetchTestUser"
                  @change="fetchTestChange"
                   :disabled="checkTestPower()"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="(d, index) in userTestData" :key="index" :value="d.username">
                    {{ d.realname }}({{ d.username }})
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8" v-if="form.id">
              <a-form-model-item ref="qualityScore" label="质量分" prop="qualityScore">
                <a-input
                  type="number"
                  v-model="form.qualityScore"
                  @blur="
                    () => {
                      $refs.qualityScore.onFieldBlur()
                    }
                  "
                   :disabled="checkTestPower()"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == '30'">
            <a-col :span="8" v-if="form.id">
              <a-form-model-item ref="testConfirmDate" label="测试时间" prop="testConfirmDate">
                <a-date-picker
                  v-model="form.testConfirmDate"
                  placeholder="测试时间"
                  :allowClear="true"
                   :disabled="checkTestPower()"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="16" v-if="form.id">
              <a-form-model-item ref="hasSendNotice" label="是否已上线" prop="hasSendNotice">
                <a-tooltip>
                  <template slot="title">
                    <span
                      >是否已上线是指【整个任务单的完成状态是以该字段为准，即使所有子任务已完成】<br />当所有子任务和缺陷都完成时，任务单创建人或迭代负责人可修改该状态。</span
                    >
                  </template>
                  <a-radio-group
                    v-model="form.hasSendNotice"
                    :disabled="
                      !(form.status == 2 && (currentUserId == form.createUserId || currentUserId == form.handlerId))
                    "
                  >
                    <a-radio value="1">未完成</a-radio>
                    <a-radio value="2">已完成并且已发通知</a-radio>
                    <a-radio value="3">已完成但无需发通知</a-radio>
                  </a-radio-group>
                </a-tooltip>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row v-if="form.taskType == '30'">
            <a-col :span="24" v-if="form.id">
              <a-form-model-item ref="testConfirm" label="测试结果" prop="testConfirm">
                <!-- <a-radio-group v-model="form.testConfirm"  :disabled="checkTestPower()">
                  <a-radio value="1">通过</a-radio>
                  <a-radio value="0">不通过</a-radio>
                </a-radio-group> -->
                <a-textarea v-model="form.testConfirm" :auto-size="{ minRows: 1, maxRows: 5 }" style="width: 100%" :disabled="checkTestPower()" :max-length="100"/>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item ref="openRangeName" label="开放范围" prop="openRangeName">
                <a-select
                  v-model="outOpenRangeName"
                  mode="multiple"
                  placeholder="输入账号或者名称查找用户"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                  @search="fetchOpenUser"
                  @change="handleOpenChange"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="(d, index) in userOpenData" :key="index" :value="d.username">
                    {{ d.realname }}({{ d.username }})
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.timeNodeCode">
            <a-col :span="24">
              <a-form-model-item ref="target" label="节点完成目标:" prop="target">
                <a-textarea v-model="form.target" :auto-size="{ minRows: 3, maxRows: 5 }" style="width: 100%" />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-divider style="margin: 10px 0" />

          <div class="info-title">
            相关附件
            <ht-upload
              ref="myUpload"
              class="upload-demo"
              multiple
              dbKey="Trd"
              busField="workTask"
              busType="workTask"
              :busKey="id"
              ftpKey="ftp"
              v-model="fileList"
              :show-file-list="false"
            >
              <a-button type="primary" v-show="form.processStatus != 1"><a-icon type="plus" />新增附件</a-button>
            </ht-upload>
            <span>
              <img src="@/assets/attention-red.png" alt="" style="width:12px;margin: 0px 5px 0px 5px;"/>
              <span style="font-size: 14px;">附件非必填，如有相关附件可以上传，例如收益计算明细，计算方法，该任务单的方案、规划、工作要求等。</span>
            </span>
          </div>
          <div style="margin-top: 10px">
            <a-table
              :columns="uploadColumns"
              :data-source="fileQueryList"
              :pagination="false"
              :rowKey="
                (record, index) => {
                  return index
                }
              "
              bordered
              class="hte-table-content"
              size="middle"
              v-show="fileQueryList.length > 0"
            >
              <a
                slot="name"
                slot-scope="text, record"
                @click="previewAttach(record.id, record.fileName)"
                href="javascript:void(0)"
                title="点击预览附件"
                style="color: blue"
                >{{ text }}</a
              >
              <span slot="uploadTime" slot-scope="text">
                {{ timeFormat(text) }}
              </span>
              <span slot="aciton" slot-scope="text, record">
                <span
                  style="color: blue; cursor: pointer"
                  @click="deletefj(record.id)"
                  type="primary"
                  v-if="record.uploader == currentUserId && form.processStatus != 1"
                  >删除</span
                >
                <span
                  style="color: blue; cursor: pointer; margin-left: 5px"
                  @click="doDownLoadBatch(record.id)"
                  type="primary"
                  v-if="form.processStatus != 1"
                  >下载</span
                >
              </span>
            </a-table>
          </div>

          <a-divider style="margin: 10px 0" />

          <div>
            <div class="info-title">
              子节点明细
              <a-button type="primary" @click="kpiAdd()" v-show="!isChangeIng && form.processStatus != 1"
                >新增</a-button
              >
              <a-button style="margin-left: 15px" @click="kpiDel()" v-show="!isChangeIng && form.processStatus != 1"
                >删除</a-button
              >
              <span style="margin-left: 15px; color: red" v-show="isChangeIng">{{ changeMsg }}</span>
            </div>
            <a-table
              :row-selection="{
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange,
                getCheckboxProps: getCheckboxProps,
              }"
              :columns="kpi.columns"
              class="hte-table-content"
              size="middle"
              :data-source="kpi.data"
              bordered
              :rowKey="
                (record, index) => {
                  return index
                }
              "
              :pagination="false"
              :loading="tableLoading"
            >
              <template slot="timeNode" slot-scope="text, record">
                <a-textarea
                  v-model="record.timeNode"
                  placeholder="请输入子节点名称，25字内"
                  :auto-size="{ minRows: 1, maxRows: 7 }"
                  @blur="
                    (value) => {
                      timeNodeCheck(value, record)
                    }
                  "
                  :maxLength="25"
                  :readOnly="(record.reportStatus == '2' || !(record.addReportUserId == currentUserId || form.createUserId === currentUserId)) && record.id && form.id? true : false"
                />
              </template>
              <template slot="jobContent" slot-scope="text, record">
                <a-textarea
                  v-model="record.jobContent"
                  placeholder="请输入子节点内容,500字内"
                  :auto-size="{ minRows: 1, maxRows: 7 }"
                  :maxLength="500"
                  :readOnly="(record.reportStatus == '2' || !(record.addReportUserId == currentUserId || form.createUserId === currentUserId)) && record.id && form.id? true : false"
                />
              </template>
              <template slot="planStartDate" slot-scope="text, record">
                <a-date-picker
                  v-model="record.planStartDate"
                  placeholder="请输入子节点开始时间"
                  :allowClear="false"
                  :disabled-date="disabledStartDate"
                  @change="
                    (date, dateString) => {
                      timeSelect(date, dateString, record, 1)
                    }
                  "
                  :disabled="(record.reportStatus == '2' || !(record.addReportUserId == currentUserId || form.createUserId === currentUserId)) && record.id && form.id? true : false"
                />
              </template>
              <template slot="completionDate" slot-scope="text, record">
                <a-date-picker
                  v-model="record.completionDate"
                  placeholder="请输入子节点完成时间"
                  :allowClear="false"
                  :disabled-date="disabledStartDate"
                  @change="
                    (date, dateString) => {
                      timeSelect(date, dateString, record, 2)
                    }
                  "
                  :disabled="(record.reportStatus == '2' || !(record.addReportUserId == currentUserId || form.createUserId === currentUserId)) && record.id && form.id? true : false"
                />
              </template>
              <template slot="addReportUserName" slot-scope="text, record">
                <a-select
                  show-search
                  :value="record.addReportUserName"
                  placeholder="输入账号或者名称查找用户"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                  @search="fetchUser"
                  @change="
                    (value, option) => {
                      handleSubChange(value, option, record)
                    }
                  "
                  :disabled="(record.reportStatus == '2' || !(record.addReportUserId == currentUserId || form.createUserId === currentUserId)) && record.id && form.id? true : false"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="(d, index) in userData" :key="index" :value="d.username">
                    {{ d.realname }}({{ d.username }})
                  </a-select-option>
                </a-select>
              </template>

              <template slot="id" slot-scope="text">
                {{ text + 'p' }}
              </template>
              <!-- <template slot="action" slot-scope="text, record">
                <span v-if="record.id" style="color:blue;" @click="applyData(record)">发起数据申请</span><br>
                <span v-if="record.id" style="color:blue;" @click="openProcessDetail(record)">数据流程</span>
              </template> -->

              <template slot="personalAttach" slot-scope="text, record">
                <a-button type="default" @click="toFile(record)" v-if="record.id"  :disabled=" !(record.addReportUserId == currentUserId || form.createUserId == currentUserId) ? true : false">附件&nbsp;<span style="size:10px;color:rgb(255, 116, 93);">({{record.fileAmount}})</span></a-button>
              </template>
            </a-table>
          </div>

          <a-divider
            style="margin: 20px 0"
            v-if="form.processInstanceId && form.processInstanceId !== '' && form.processStatus == 1"
          />
          <div v-if="form.processInstanceId && form.processInstanceId !== '' && form.processStatus == 1">
            <div class="info-title">审批记录</div>
            <ht-approval
              ref="childrenRef"
              :process-instance-id="form.processInstanceId"
              :options="options"
              :custom="custom"
              @submit="afterSubmit"
              @reject="afterReject"
              @back="backAction"
              @cancelSubmit="afterCancelSubmit"
              :before-fill-opinion="saveNotifyOpinion"
              :before-submit="beforeSubmit"
              :before-reject="beforeReject"
              :show-task-history="true"
              :history-dialog="historyDialog"
              :task-load="taskLoad"
              :message-id="messageId"
              :show-upload-btn="false"
              :hidden-task-def-key="hiddenTaskDefKey"
              :snapshotConfigs="snapshotConfigs"
            >
            </ht-approval>
          </div>
        </a-form-model>
        <div class="btn-box" v-if="form.processStatus != 1">
          <a-button style="margin-right: 15px" @click="doSubmit(false)" v-show="!isChangeIng">保存</a-button>
          <a-button
            style="margin-right: 15px"
            type="primary"
            @click="doSubmit(true)"
            v-show="form.id != '' && form.status == '1'"
            >确认任务单</a-button
          >
          <a-button
            style="margin-right: 15px"
            @click="sendTask"
            v-show="form.id != '' && form.status != '1' && form.createUserId === currentUserId"
            >发送娅米消息通知</a-button
          >
        </div>
      </div>
    </div>

    <pagination-select
      :title="associated.title"
      :searchPlaceholder="associated.searchPlaceholder"
      :visible="associated.visible"
      :url="associated.url"
      :columns="associated.columns"
      @hatchHandleOk="associatedHandleOk"
    />

    <a-modal
      v-model="visibleModelHistory"
      width="70vw"
      :bodyStyle="{ padding: '10px', backgroundColor: '#f4f5fa' }"
      title="变更历史"
      :footer="null"
      :key="id"
    >
      <task-change-history :hid="id"></task-change-history>
    </a-modal>

    <a-modal
      v-model="visibleModelProcess"
      width="70vw"
      :bodyStyle="{ padding: '10px', backgroundColor: '#f4f5fa' }"
      title="流程状态"
      :footer="null"
      :key="processId"
    >
      <task-tech-process
        :detailId="processId"
        :modalType="processType"
        :processInstanceId="form.processInstanceId"
      ></task-tech-process>
    </a-modal>

    <process-user-select :columns="selUserCols" @selectUserConfirm="selectUserConfirm"  ref="processUserSelect" />

    <a-modal class="selectedPerson" title="附件信息" :visible="attachVisible" width="80vw" @cancel="handleAttachClose()" :footer="null" :destroyOnClose="true" :key="'attach'+busKey">
      <attach-tab :bus-field="busField" :bus-key="busKey" :bus-type="busType" @closeAttachModal="handleAttachClose()"></attach-tab>
    </a-modal>
  </div>
</template>

<script>
import { getAction, postAction,previewAttach } from '@/api/manage'
import moment from 'moment'
import '@/config/upload.install.js'
import Vue from 'vue'
import { Modal } from 'ant-design-vue'
import { ACCESS_TOKEN, USER_INFO, USER_NAME } from '@/store/mutation-types'
import { getParamValFromUrl, strNotNull, formatFileSize, endWith } from '@/utils/common.js'
import {filterHasPermission} from '@/utils/hasPermission'

const uploadColumns = [
  {
    title: '附件名称',
    dataIndex: 'fileName',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '上传人',
    dataIndex: 'uploaderName',
    width: '10%',
  },
  {
    title: '上传时间',
    dataIndex: 'uploadTime',
    align: 'center',
    width: '15%',
    scopedSlots: { customRender: 'uploadTime' },
  },
  {
    title: '操作',
    dataIndex: 'aciton',
    align: 'center',
    scopedSlots: { customRender: 'aciton' },
    width: '10%',
  },
]

export default {
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    PaginationSelect: () => import('@/components/tools/PaginationSelect'),
    TaskChangeHistory: () => import('@views/myTask/TaskChangeHistory'),
    TaskTechProcess: () => import('@views/myTask/TaskTechProcess'),
    ProcessUserSelect: () => import('@/components/tools/projectBuildStup/ProcessUserSelect'),
    htApproval: () => import('@/config/ht-approval.umd.min.js'),
    AttachTab: () => import('@/views/projectBuildTask/AttachTab')
  },
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'projectTaskAdd',
      },
      tabColumnsOut: [
        {
          dataIndex: 'memberUserName',
          title: '账号',
        },
        {
          dataIndex: 'memberRealName',
          title: '姓名',
        },
      ],
      associated: {
        visible: false,
        title: '请选择项目',
        searchPlaceholder: '输入项目编号或名称查询',
        url: '/projectBuild/queryFindProjectByTask',
        columns: [
          {
            title: '项目编号',
            dataIndex: 'projectNo',
            align: 'center',
          },
          {
            title: '项目名称',
            dataIndex: 'projectName',
            align: 'center',
          },
        ],
      },
      uploadColumns,
      selectedRowKeys: [],
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      tableSelectKey: '',
      form: {
        id: '',
        taskType: '',
        projectBuildId: '',
        projectNo: '',
        projectName: '',
        timeNodeCode: '',
        mainDeptId: '',
        mainDeptName: '',
        createUserName: '',
        createDate: '',
        startDate: '',
        endDate: '',
        target: '',
        taskBuildType: '3',
        taskNo: '',
        versionNo: '',
        handlerId: '',
        handlerName: undefined,
        hasSendNotice: '1',
        projectTypeSubCategory: '',
        productSystem: '',
        productSystemName: '',
        openRange: '',
        openRangeName: '',
        createType: 0,
        businessConfirm: '',
        processInstanceId: '',
        processStatus: '',
        qualityScore: '',
        testConfirm: '',
        testUserId: '',
        testUserName: undefined,
        testConfirmDate: '',
      },
      rules: {
        projectNo: [{ required: true, message: '请选择对应项目', trigger: 'change' }],
        timeNodeCode: [{ required: true, message: '请选择对应项目节点', trigger: 'change' }],
        handlerName: [{ required: true, message: '请选择迭代负责人', trigger: 'blur' }],
        taskName: [
          { required: true, message: '请输入任务单名称', trigger: 'blur' },
          { min: 1, max: 50, message: '任务单名称不超过50个字符', trigger: 'blur' },
        ],
        versionNo: [
          { required: true, message: '请输入版本号', trigger: 'blur' },
          { pattern: /[vV]\d{1,2}\.\d{1,2}\.\d{1,2}$/, message: '格式v1.0.0 || V1.0.0 ', trigger: 'blur' },
        ],
        productSystem: [{ required: true, message: '请选择产品系统', trigger: 'change' }],
        startDate: [{ required: true, message: '请选择任务开始时间', trigger: 'change' }],
        endDate: [{ required: true, message: '请选择任务完成时间', trigger: 'change' }],
        businessConfirm: [{ required: true, message: '请选择需要审批确认', trigger: 'blue' }],
      },
      url: {
        save: '/projectWorkTask/saveProjectTask',
        getAttachInfo: '/tp/attach/getAttaches',
        getProjectTask: '/projectWorkTask/queryProjectTaskById',
        sendTask: '/projectWorkTask/sendTask',
        initTimeNodeOption: '/projectBuildTime/queryListByBuildId',
        getMaxAddTimeNodeCode: '/projectBuildTime/getMaxAddTimeNodeCode',
        selectMemberUrl: '/projectBuildTeam/queryTeamListByBuildId',
        getProjectBuildById: '/projectBuild/queryById',
        codeInfoList: '/manage/codeInfo/list',
        getUserList: '/lib/hteFileClass/getUserListOnlyUpms',
        downLoadBatch: '/common/downLoadBatch',
        deleteBatch: '/tp/attach/delete',
        getVersionTopFive: '/projectWorkTask/getVersionTopFive',
        listByAcceptApplyId: '/projectCompleteAcceptOpinion/listByAcceptApplyId',
        checkProjectInChange: '/projectWorkTask/checkProjectInChange',
        publishItTask: '/projectWorkTask/publishItTask',
      },
      kpi: {
        columns: [
          {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            width: 50,
            customRender: (text, record, index) => `${index + 1}`,
          },
          {
            title: '子节点名称',
            dataIndex: 'timeNode',
            scopedSlots: { customRender: 'timeNode' },
          },
          {
            title: '子节点内容',
            dataIndex: 'jobContent',
            scopedSlots: { customRender: 'jobContent' },
          },
          {
            title: '子节点开始时间',
            dataIndex: 'planStartDate',
            width: '15%',
            scopedSlots: { customRender: 'planStartDate' },
            sorter: (a, b) => a.planStartDate.localeCompare(b.planStartDate),
          },
          {
            title: '子节点完成时间',
            dataIndex: 'completionDate',
            width: '15%',
            scopedSlots: { customRender: 'completionDate' },
            sorter: (a, b) => a.completionDate.localeCompare(b.completionDate),
          },
          {
            title: '具体执行人员',
            dataIndex: 'addReportUserName',
            scopedSlots: { customRender: 'addReportUserName' },
            width: '15%',
          },
          {
            title: '个人附件',
            dataIndex: 'personalAttach',
            scopedSlots: { customRender: 'personalAttach' },
            width: '100px'
          },
        ],
        data: [],
        selRowIds: [],
      },
      fileList: [],
      fileQueryList: [],
      id: '',
      addFlag: false,
      currentUserId: '',
      timeNodeCodeOptions: [],
      timeListData: [],
      nowDate: moment().format('YYYY-MM-DD'),
      maxTimeNodeCode: '',
      startTimeFlag: false,
      projectNoAndName: '',
      productSystemOptions: [],
      fetching: false,
      userData: [],
      userOpenData: [],
      userHandleData: [],
      userTestData: [],
      outOpenRangeName: undefined,
      versionTip: '',
      casProductSystemOptions: [],
      casModel: [],
      acceptApplyId: null,
      isChangeIng: false,
      changeMsg: '',
      visibleModelHistory: false,
      processId: '',
      visibleModelProcess: false,
      columnsAddFlag: false,
      selUserCols: [],
      processType: '',
      //processInstanceId: 'fde08e55-57fc-11ec-8f44-0242ac110003',
      options: {
        request: {
          baseUrl: this.API_BASE_URL, // 业务系统根路径
          timeOut: 10000, // 请求超时时间
          interceptors: (config) => {
            config.headers['X-Access-Token'] = Vue.ls.get(ACCESS_TOKEN)
            return config
          },
        },
        userId: Vue.ls.get(USER_NAME),
      },
      messageId: '', // 工作台URL里面的msgId参数
      hiddenTaskDefKey: 'submit',
      custom: {
        budgetAmount: 0,
      },
      historyDialog: {
        // 审批历史模态框属性
      },
      snapshotConfigs: [
        {
          type: 'ref',
          value: 'imageWrapper',
        },
      ],
      attachVisible:false,
      busField: 'dailyTaskAttach',
      busKey: '',
      busType: 'dailyTaskAttach',
      tableLoading:false,
      sbFlag: false
    }
  },
  created() {
    const obj = this.$route.query
    this.id = obj.id
    if (this.id) {
      this.initData(this.id)
    } else {
      this.addFlag = true
      this.form.mainDeptId = Vue.ls.get(USER_INFO).deptId
      this.form.mainDeptName = Vue.ls.get(USER_INFO).deptName
      this.form.createUserName = Vue.ls.get(USER_INFO).realname
      this.initSelectData()
      var acceptApplyId = getParamValFromUrl('acceptApplyId')
      var projectBuildId = getParamValFromUrl('projectBuildId')
      this.sbFlag = getParamValFromUrl('sbFlag')
      if (strNotNull(acceptApplyId) && strNotNull(projectBuildId)) {
        this.acceptApplyId = acceptApplyId
        this.form.projectBuildId = projectBuildId
        this.form.timeNodeCode = '70'
        this.form.createType = 1
        getAction(this.url.getProjectBuildById, { id: projectBuildId }).then((resProject) => {
          this.associatedHandleOk([resProject.result])
        })
      }
      if (this.sbFlag) {
        this.form.projectBuildId = projectBuildId
        getAction(this.url.getProjectBuildById, { id: projectBuildId }).then((resProject) => {
          this.associatedHandleOk([resProject.result])
        })
      }
    }
    this.currentUserId = Vue.ls.get(USER_INFO).username
  },
  methods: {
    casLoadData(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      targetOption.loading = true
      let arr = []
      this.productSystemOptions.map((item) => {
        if (item.title == targetOption.title) {
          arr.push({ value: item.value, label: item.label, title: item.label })
        }
      })
      targetOption.children = arr
      targetOption.loading = false
      this.casProductSystemOptions = [...this.casProductSystemOptions]
    },
    casProductSystemOnChange(value, selectedOptions) {
      this.form.productSystem = selectedOptions && selectedOptions[1] ? selectedOptions[1].value : ''
      this.form.productSystemName = selectedOptions && selectedOptions[1] ? selectedOptions[1].label : ''
      this.$set(this.form, 'productSystem', selectedOptions && selectedOptions[1] ? selectedOptions[1].value : '')
      this.$set(this.form, 'productSystemName', selectedOptions && selectedOptions[1] ? selectedOptions[1].label : '')
      if (this.form.productSystem) {
        this.getVersionTopFive(this.form.productSystem)
      }
    },
    disabledEndDate(current) {
      return current < moment(this.form.startDate).subtract(1, 'days').endOf('day')
    },
    fetchHandleUser(val) {
      if (val) {
        this.userHandleData = []
        this.fetching = true
        getAction(this.url.getUserList, { name: val }).then((res) => {
          if (res.success) {
            this.userHandleData = res.result
            this.fetching = false
          }
        })
      }
    },
    // 迭代负责人
    fetchHandleChange(value, option) {
      this.$set(this.form, 'handlerId', value)
      let text = option.componentOptions.children[0].text.trim();
      let realText = text ? text.split("(")[0] : "";
      this.$set(this.form, 'handlerName', realText)
    },
    fetchTestUser(val) {
      if (val) {
        this.userTestData = []
        this.fetching = true
        getAction(this.url.getUserList, { name: val }).then((res) => {
          if (res.success) {
            this.userTestData = res.result
            this.fetching = false
          }
        })
      }
    },
    // 测试员
    fetchTestChange(value, option) {
      this.$set(this.form, 'testUserId', value)
      let text = option.componentOptions.children[0].text.trim();
      let realText = text ? text.split("(")[0] : "";
      this.$set(this.form, 'testUserName', realText)
    },
    fetchOpenUser(val) {
      if (val) {
        this.userOpenData = []
        this.fetching = true
        getAction(this.url.getUserList, { name: val }).then((res) => {
          if (res.success) {
            this.userOpenData = res.result
            this.fetching = false
          }
        })
      }
    },
    // 开放范围
    handleOpenChange(value, option) {
      this.$set(this.form, 'openRange', value.join(','))
      let arr = []
      option.forEach((item) => {
        let text = item.componentOptions.children[0].text ? item.componentOptions.children[0].text.trim() : ''
        let realText = text ? text.split("(")[0] : "";
        arr.push(realText)
      })
      this.$set(this.form, 'openRangeName', arr.join(','))
    },
    loadRange(nameList) {
      if (nameList) {
        this.userOpenData = []
        this.fetching = true
        getAction(this.url.getUserList, { nameList: nameList }).then((res) => {
          if (res.success) {
            this.userOpenData = res.result
            this.fetching = false
          }
        })
      }
    },
    fetchUser(val) {
      if (val) {
        this.userData = []
        this.fetching = true
        getAction(this.url.getUserList, { name: val }).then((res) => {
          if (res.success) {
            this.userData = res.result
            this.fetching = false
          }
        })
      }
    },
    // 明细处理人
    handleSubChange(value, option, record) {
      let index = this.kpi.data.findIndex((item) => item.key === record.key)
      if (index != -1) {
        this.kpi.data[index].addReportUserId = value
        let text = option.componentOptions.children[0].text.trim();
        let realText = text ? text.split("(")[0] : "";
        this.kpi.data[index].addReportUserName = realText
      }
    },
    initSelectData() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '产品系统', isdel: 0, pageSize: -1 })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            let uniqueArr = []
            let parentid = ''
            this.productSystemOptions = []
            this.casProductSystemOptions = []
            if (list != null) {
              list.records.map((item) => {
                vm.productSystemOptions.push({ value: item.code, label: item.name, title: item.parentid })
                if (uniqueArr.indexOf(item.parentid) == -1) {
                  uniqueArr.push(item.parentid)
                  vm.casProductSystemOptions.push({
                    value: item.parentid,
                    label: item.parentid,
                    isLeaf: false,
                    title: item.parentid,
                  })
                }
                if (item.code == this.form.productSystem) {
                  parentid = item.parentid
                }
              })
              if (this.form.productSystem) {
                this.casProductSystemOptions.map((item) => {
                  let arr = []
                  vm.productSystemOptions.map((subItem) => {
                    if (subItem.title == item.value) {
                      arr.push({ value: subItem.value, label: subItem.label, title: subItem.label })
                    }
                  })
                  item.children = arr
                })
                this.casProductSystemOptions = [...this.casProductSystemOptions]
                this.casModel = []
                this.casModel.unshift(parentid)
                this.casModel.push(this.form.productSystem)
              }
            }
          } else {
            this.$message.warning('查询产品系统失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询产品系统失败:' + res.message)
        })
    },
    getVersionTopFive(value) {
      var vm = this
      getAction(this.url.getVersionTopFive, { type: value }).then((res) => {
        if (res.code == 200 && res.result) {
          vm.versionTip = res.result.join(',')
        }
      })
    },
    getMaxTimeNode() {
      if (this.maxTimeNodeCode && this.maxTimeNodeCode !== '') {
        let num = parseInt(this.maxTimeNodeCode.substring(3)) + 1
        this.maxTimeNodeCode = 'add' + (Array(3).join('0') + num).slice(-3)
      } else {
        this.maxTimeNodeCode = 'add001'
      }
    },
    getMaxAddTimeNodeCode(id) {
      getAction(this.url.getMaxAddTimeNodeCode, { projectBuildId: id }).then((res) => {
        this.maxTimeNodeCode = res.result || ''
      })
    },
    associatedHandleOk(record) {
      if (record != null && record.length > 0) {
        this.form.projectNo = record[0].projectNo
        this.form.projectName = record[0].projectName
        this.form.projectBuildId = record[0].id
        if (!record[0].projectClass) {
          this.$message.warning('项目信息有误，缺少项目分类编码:' + record[0].projectNo)
          return 
        }
        this.form.taskType = record[0].projectClass || ''
        
        this.projectNoAndName = record[0].projectNo + ' && ' + record[0].projectName
        this.form.projectTypeSubCategory = record[0].projectTypeSubCategory
        // this.form.mainDeptName = record[0].mainDeptName
        // this.form.createUserName = record[0].createUserName

        this.checkProjectInChange(record[0].id)
        this.initTimeNodeOption(this.form.projectBuildId)
        this.getMaxAddTimeNodeCode(this.form.projectBuildId)
      }
      this.associated.visible = false
    },
    checkProjectInChange(projectBuildId) {
      getAction(this.url.checkProjectInChange, { projectBuildId: projectBuildId })
        .then((res) => {
          if (res.code != 200) {
            this.changeMsg = res.message
            this.isChangeIng = true
          } else {
            this.isChangeIng = false
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目是否处理变更过程中失败:' + res.message)
          this.changeMsg = '查询项目是否处理变更过程中失败'
          this.isChangeIng = true
        })
    },
    timeFormat(time) {
      if (time) {
        return moment(time).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    disabledStartDate(current) {
      return (
        current < moment(this.form.startDate).subtract(1, 'days').endOf('day') ||
        current > moment(this.form.endDate).endOf('day')
      )
    },
    timeSelect(date, dateString, record, id) {
      let startDateStr = record.planStartDate ? moment(record.planStartDate).format('YYYY-MM-DD') : record.planStartDate
      let endDateStr = record.completionDate
        ? moment(record.completionDate).format('YYYY-MM-DD')
        : record.completionDate
      let formStartDateStr = this.form.startDate
      let formEndDateStr = this.form.endDate
      if (!formStartDateStr || !formEndDateStr) {
        this.$message.warning('请先填写单头的开始时间和结束时间')
        if (id === 1) {
          this.kpi.data.forEach((item) => {
            // bugger todo
            if (item.key === record.key) {
              item.planStartDate = ''
            }
          })
        } else {
          this.kpi.data.forEach((item) => {
            if (item.key === record.key) {
              item.completionDate = ''
            }
          })
        }
        return
      }
      if (startDateStr && startDateStr != '' && endDateStr && endDateStr != '') {
        if (moment(startDateStr).diff(moment(endDateStr), 'days') > 0) {
          this.$message.warning('开始时间不能大于完成时间')
          if (id === 1) {
            this.kpi.data.forEach((item) => {
              if (item.key === record.key) {
                item.planStartDate = ''
              }
            })
          } else {
            this.kpi.data.forEach((item) => {
              if (item.key === record.key) {
                item.completionDate = ''
              }
            })
          }
          return
        }
      }
      if (id === 1) {
        if (!startDateStr) {
          this.$message.warning('请填写子任务单开始时间')
          this.kpi.data.forEach((item) => {
            if (item.key === record.key) {
              item.planStartDate = ''
            }
          })
          return
        }
        if (moment(startDateStr).diff(moment(formEndDateStr), 'days') > 0) {
          this.$message.warning('子任务单开始时间不允许大于单头结束时间')
          this.kpi.data.forEach((item) => {
            if (item.key === record.key) {
              item.planStartDate = ''
            }
          })
          return
        }
        this.kpi.data.forEach((item) => {
          if (item.key === record.key) {
            item.planStartDate = dateString
          }
        })
      } else {
        if (!endDateStr) {
          this.$message.warning('请填写子任务单结束时间')
          this.kpi.data.forEach((item) => {
            if (item.key === record.key) {
              item.completionDate = ''
            }
          })
          return
        }
        if (moment(endDateStr).diff(moment(formEndDateStr), 'days') > 0) {
          this.$message.warning('子任务单结束时间不允许大于单头结束时间')
          this.kpi.data.forEach((item) => {
            if (item.key === record.key) {
              item.completionDate = ''
            }
          })
          return
        }

        this.kpi.data.forEach((item) => {
          if (item.key === record.key) {
            item.completionDate = dateString
          }
        })
      }
    },
    timeNodeCheck(e, record) {
      const _this = this
      let flag = false
      this.kpi.data.forEach((item) => {
        if (item.key != record.key) {
          if (e.target.value == item.timeNode) {
            _this.$message.warning('子节点名称不允许相同')
            flag = true
          }
        }
      })
      if (flag) {
        this.kpi.data.forEach((item) => {
          if (item.key === record.key) {
            item.timeNode = ''
          }
        })
      }
    },
    initEngineeProjectAcceptTask() {
      const that = this
      getAction(that.url.listByAcceptApplyId, { acceptApplyId: this.acceptApplyId })
        .then((res) => {
          if (res.code === 200) {
            if (res.result && res.result.length > 0) {
              res.result.forEach((item) => {
                that.kpiAdd(item.targetTypeTxt, item.problemDescript)
              })
            }
          } else {
            const msg = res.message == null ? res.result : res.message
            that.$message.error(msg)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    kpiAdd(timeNode, jobContent) {
      if (!this.form.timeNodeCode) {
        this.$message.warning('请先选择项目节点')
        return
      }

      if (!this.form.startDate) {
        this.$message.warning('请先选择节点开始时间')
        return
      }

      this.getMaxTimeNode()
      this.kpi.data.unshift({
        key: this.kpi.data.length + 1 + new Date().getTime(),
        timeNode: timeNode == null ? '' : timeNode,
        jobContent: jobContent == null ? '' : jobContent,
        planStartDate: '',
        completionDate: '',
        completionDateAudit: '',
        planStartDateAudit: '',
        implementationCycle: '',
        implementationCycleAudit: '',
        addReportUserId: undefined,
        addReportUserName: undefined,
        timeNodeCode: this.maxTimeNodeCode,
        id: '',
        projectBuildId: this.form.projectBuildId,
        parentCode: this.form.timeNodeCode,
      })
    },
    kpiDel() {
      if (this.kpi.selRowIds.length == 0) {
        this.$message.warning('请选择要删除的明细记录')
        return
      }

      if (this.kpi.data.length == 1) {
        this.$message.warning('该任务单只有一条子任务，不能删除')
        return
      }
      const that = this;
      Modal.confirm({
        title: '提示',
        content: '删除子任务之前请先保存任务信息，避免数据丢失',
        onOk() {
          const list = that.kpi.selRowIds.map(function (item) {
            return item.id
          })
          that.delAjax(list)
          that.kpi.selRowIds = []
          that.selectedRowKeys = [] 
        },
        onCancel() {},
      })
    },
    delAjax(list) {
        // todo ajax 刷新整个页面 
      postAction('/projectWorkTask/detailBatchDelete', {"list":list,"taskBuildType":3})
      .then((res) => {
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.initData(this.form.id)
        } else {
          const msg = res.message == null ? res.result : res.message
          this.$message.error(msg)
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    sendTask() {
      const that = this
      postAction(that.url.sendTask, that.form)
        .then((res) => {
          if (res.code === 200) {
            that.$message.success('发送成功')
          } else {
            const msg = res.message == null ? res.result : res.message
            that.$message.error(msg)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    doSubmit(saveFlag) {
      this.$refs.ruleForm.validate((err, values) => {
        if (!err) {
          this.$message.error('请填写完整任务单头信息')
          return
        }
        if (this.form.startDate == '') {
          this.$message.error('请填写完整任务单头信息')
          return
        }
        let flag = false
        let timeFlag = false

        // if (this.kpi.data.length === 0) {
        //   this.$message.error('子任务明细没填写完整');
        //   return;
        // }

        if (this.kpi.data.length > 0) {
          this.kpi.data.forEach((item) => {
            if (
              item.timeNode === '' ||
              item.jobContent === '' ||
              item.planStartDate === '' ||
              item.completionDate === '' ||
              item.addReportUserId === '' ||
              !item.addReportUserId ||
              item.addReportUserName === ''
            ) {
              flag = true
            } else {
              if (
                moment(item.planStartDate).diff(moment(this.form.startDate), 'days') < 0 ||
                moment(item.planStartDate).diff(moment(this.form.endDate), 'days') > 0
              ) {
                timeFlag = true
              }
              if (
                moment(item.completionDate).diff(moment(this.form.startDate), 'days') < 0 ||
                moment(item.completionDate).diff(moment(this.form.endDate), 'days') > 0
              ) {
                timeFlag = true
              }
            }
          })
        }

        if (timeFlag) {
          this.$message.error('子任务单的时间不在任务单头时间范围内')
          return
        }

        if (flag) {
          this.$message.error('子任务明细没填写完整')
          return
        }

        this.kpi.data.forEach((item) => {
          item.planStartDateAudit = item.planStartDate
          item.completionDateAudit = item.completionDate

          let startDate = new Date(item.planStartDate)
          let endDate = new Date(item.completionDate)

          item.implementationCycle = (Math.floor(endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000)).toFixed(
            0
          )
          item.implementationCycleAudit = item.implementationCycle
        })
        this.form.timeDetail = this.kpi.data

        if (this.form.status && this.form.status != '1') {
          saveFlag = true
        }

        this.form.saveFlag = saveFlag
        // this.form.taskName = this.form.projectName
        if (saveFlag && this.form.status == 1 && this.form.taskType == '30' && this.form.businessConfirm == '1') {
          this.checkAndPublish()
          return
        }
        const that = this
        postAction(that.url.save, that.form)
          .then((res) => {
            if (res.code === 200) {
              if (!this.form.status) {
                that.$message.success('创建任务单成功，需要点击确认任务单才会生效', 5)
              } else {
                that.$message.success('保存成功')
              }
              that.form.id = res.result
              that.id = res.result
              if (that.addFlag) {
                that.bindBusKey()
                that.$router.push({ path: '/projectTaskAdd', query: { id: res.result } })
              }
              that.initData(that.form.id)
            } else {
              const msg = res.message == null ? res.result : res.message
              that.$message.error(msg)
            }
          })
          .catch((err) => {
            console.log(err)
          })
      })
    },
    checkAndPublish() {
      if (this.fileQueryList.length == 0) {
        this.$message.error('选择了【需要审批确认】，需要上传【需求规格说明书】附件')
        return
      }
      this.selUserCols = [{ label: '相关负责人', field: 'departmentUser', username: '', realname: '', required: true,placeholder:'必填，可选多人'},
                { label: '业务负责人', field: 'managerUser', username: '', realname: '', required: false,placeholder:'非必填，不填则跳过审批' }]
      this.$refs.processUserSelect.doSelect()
    },
    radioChange() {
      if (this.form.businessConfirm == '1') {
        this.$message.success('选择是则需要上传《需求规格说明书》提交给业务负责人确认审核')
      }
    },
    selectUserConfirm(cols) {
      if (cols != null && cols.length > 0) {
        var data = {}
        cols.forEach((item) => {
          var key = item.field
          data[key] = item.username
        })
        let vm = this
        //参数组装完毕，发起流程
        postAction(this.url.publishItTask, { id: this.form.id, approvalPerson: data })
          .then((res) => {
            if (res.code == 200) {
              this.$message.success('发起审批流程成功')
              this.initData(this.form.id)
            } else {
              this.$message.warning('发起流程失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('发起流程异常:' + res.message)
          })
      } else {
        this.$message.warning('未选中操作员')
      }
    },
    initTimeNodeOption(id) {
      var vm = this
      vm.timeNodeCodeOptions = []
      if (this.form.createType != 1) {
        vm.form.timeNodeCode = ''
      }
      getAction(vm.url.initTimeNodeOption, { projectBuildId: id }).then((res) => {
        if (res.code === 200) {
          vm.timeListData = res.result || []
          let newarr = vm.timeListData.filter((item) => {
            return this.form.createType == 1 || this.form.status == 2 ? true : item.reportStatus == null || item.reportStatus != '2'
          })
          newarr.forEach((element) => {
            vm.timeNodeCodeOptions.push({
              label: element.timeNode,
              value: element.timeNodeCode,
            })
          })
          if (this.form.createType == 1) {
            this.timeNodeCodeChange(this.form.timeNodeCode)
          }
          if (this.sbFlag) {
            this.form.timeNodeCode = '20'
            this.timeNodeCodeChange(this.form.timeNodeCode)
          }
        } else {
          //const msg = res.message == null ? res.data : res.message;
          this.$message.error(res.message)
        }
      })
    },
    timeNodeCodeChange(value, option) {
      let index = this.timeListData.findIndex((item) => item.timeNodeCode === value)
      if (index != -1) {
        let obj = this.timeListData[index]
        this.form.target = obj.jobContent
        if (this.form.taskType != '30') {
          this.form.startDate = obj.planStartDateAudit ? obj.planStartDateAudit : obj.planStartDate
          this.form.endDate = obj.completionDateAudit ? obj.completionDateAudit : obj.completionDate
          if (!this.form.startDate) {
            this.form.startDate = ''
            this.startTimeFlag = true
          } else {
            this.startTimeFlag = false
          }
          if (this.form.createType == 1 && !this.form.id) {
            this.initEngineeProjectAcceptTask()
          }
        }
      }
    },
    initData(id) {
      getAction(this.url.getProjectTask, { id: id }).then((res) => {
        if (res.code === 200) {
          this.checkProjectInChange(res.result.projectBuildId)
          this.initTimeNodeOption(res.result.projectBuildId)
          this.getMaxAddTimeNodeCode(res.result.projectBuildId)
          this.form = res.result
          // Vue 不能检测数组和对象的变化
          this.$set(this.form, 'timeNodeCode', this.form.timeNodeCode)
          getAction(this.url.getProjectBuildById, { id: this.form.projectBuildId }).then((resProject) => {
            this.form.projectNo = resProject.result.projectNo
            this.form.projectName = resProject.result.projectName
            this.projectNoAndName = resProject.result.projectNo + ' && ' + resProject.result.projectName
          })

          // drcary
          if (this.form.openRange) {
            this.outOpenRangeName = this.form.openRange.split(',')
            this.loadRange(this.form.openRange)
          }
          this.initSelectData()
          if (this.form.taskType == '10' && !this.columnsAddFlag) {
            this.kpi.columns.splice(0, 1, {
              title: '编号',
              dataIndex: 'id',
              key: 'id',
              align: 'center',
              width: '10%',
              scopedSlots: { customRender: 'id' },
            })
            this.kpi.columns.push({
              title: '操作',
              dataIndex: 'action',
              key: 'action',
              align: 'center',
              width: '10%',
              scopedSlots: { customRender: 'action' },
            })
            this.columnsAddFlag = true
          }
          this.kpi.data = res.result.timeDetail
          this.kpi.data.forEach((item, index) => {
            item.key = index + 1
          })
          this.id = this.form.id
          this.loadAttachInfo()
          this.$set(this.form, 'projectNo', this.form.projectNo)
          this.$set(this.form, 'projectName', this.form.projectName)
          this.$set(this.form, 'businessConfirm', this.form.businessConfirm + '')
          //this.$set(this.form, 'testConfirm', this.form.testConfirm + '')

          this.freshFileAmounts()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    loadAttachInfo() {
      getAction(this.url.getAttachInfo, {
        dbKey: 'Trd',
        busKey: this.id,
        busField: 'workTask',
        busType: 'workTask',
        ftpKey: 'ftp',
      }).then((res) => {
        this.fileQueryList = res.data || []
      })
    },
    previewAttach(attachId, fileName) {
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        this.doDownLoadBatch(attachId)
        return
      }

      let params={
        id:attachId,
        ftpKey:'ftp'
      };
      previewAttach(params).then(result=>{
        const url=URL.createObjectURL(result)
        window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
      }).catch(err => {
        this.$message.warning('下载文件失败');
      })
    },
    doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        let downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      let iframe = document.getElementById('_attachToolView_downloadfile_frame')
      iframe.src =
        this.API_BASE_URL +
        this.url.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)
    },
    // 绑busKey
    bindBusKey() {
      if (this.fileList.length > 0) {
        const ids = this.fileList.map(function (item) {
          return item.id
        })
        const jsona = { dbKey: 'Trd', id: ids.toString(), busKey: this.form.id }
        var jsonStr = JSON.stringify(jsona)
        this.$refs.myUpload.bindBusKey(jsonStr)
      }
    },
    deletefj(id) {
      const that = this
      this.$confirm({
        title: '是否确认删除？',
        onOk() {
          postAction(that.url.deleteBatch, { id: id, busField: 'workTask', busType: 'workTask', ftpKey: 'ftp' })
            .then((res) => {
              if (res.code == 1) {
                that.$message.success('删除成功')
                that.fileQueryList.splice(
                  that.fileQueryList.findIndex((item) => item.id === id),
                  1
                )
                that.fileList.splice(
                  that.fileList.findIndex((item) => item.id === id),
                  1
                )
              } else {
                that.$message.warning('删除失败:' + res.msg)
              }
            })
            .catch((res) => {
              that.$message.warning('删除失败:' + res.msg)
            })
        },
        onCancel() {},
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.kpi.selRowIds = selectedRows
      this.selectedRowKeys = selectedRowKeys
    },
    getCheckboxProps(record) {
      return {
        props: {
          disabled: (record.reportStatus == '2' || !(record.addReportUserId == this.currentUserId || this.form.createUserId == this.currentUserId)) && record.id && this.form.id ? true : false
        },
      }
    },
    dateSelect(date, dateString, id) {
      let startDateStr = this.form.startDate
      let endDateStr = this.form.endDate
      if (startDateStr && startDateStr != '' && endDateStr && endDateStr != '') {
        if (moment(startDateStr).diff(moment(endDateStr), 'days') > 0) {
          this.$message.warning('开始时间不能大于完成时间')
          if (id === 1) {
            this.form.startDate = ''
          } else {
            this.form.endDate = ''
          }
          return
        }
      }
      if (id === 1) {
        this.form.startDate = dateString
      } else {
        this.form.endDate = dateString
      }
    },
    openHistory() {
      this.visibleModelHistory = true
    },
    openProcessHistory() {
      this.visibleModelProcess = true
      this.processType = this.form.taskType
    },
    applyData() {
      window.open(`http://10.254.2.37:8383/portal/portalpage/index.jsp?yamitoken=\$YAMITOKEN\$`, '_blank')
    },
    openProcessDetail(record) {
      this.visibleModelProcess = true
      this.processType = ''
      this.processId = record.id + 'p'
    },
    checkTestPower() {
      // if (this.form.status == 2 && this.form.hasSendNotice && this.form.hasSendNotice != '1') {
      //   return true
      // }
      if (filterHasPermission('projectWorkTask:permission:30')) {
        return false
      } 
      return true
    },
    //-------------流程回调------start
    checkOptionValue() {
      var options = this.$refs.childrenRef.data
      if (options == '' || options == null || options == undefined) {
        // this.$message.warning('审批意见不能为空', 3000)
        return false
      } else {
        return true
      }
    },
    beforeSubmit(res) {
      return true
    },
    afterSubmit(res) {
      return true
    },
    beforeReject(res) {
      if (this.checkOptionValue()) {
        return true
      } else {
        return false
      }
    },
    afterReject(res) {
      // 用户点击驳回后成功返回后的处理
    },
    backAction(res) {
      return true
    },
    //撤回后
    afterCancelSubmit() {
      return true
    },
    // 生成抄送任务方法，非必须
    sendNotify() {
      // 参数一：抄送人，参数二：工作台打开详情链接
      // this.$refs.childrenRef.saveBpmNotify('liangyh', 'http://xxxxx.com')
    },
    saveNotifyOpinion() {
      // 保存抄送意见前置动作
      return true
    },
    taskLoad(task) {},
    //-------------流程回调------end
    toFile(record){
      this.busKey = record.id+''
      this.attachVisible=true
    },
    handleAttachClose(){
      this.attachVisible=false;
      this.freshFileAmounts()
    },
    freshFileAmounts(){
      if (this.busKey) {
        const index = this.kpi.data.findIndex(item => item.id == this.busKey)
        if (index > -1) {
          this.getAttachNum(this.kpi.data[index],index)
        }
      } else {
        this.kpi.data.forEach((data,index)=>{
          this.getAttachNum(data,index)
        })
      }
    },
    getAttachNum(data,index) {
       getAction(this.url.getAttachInfo,{dbKey:'Trd',busKey:data.id,busField:this.busField,busType:this.busType}).then(res=>{
        if(res.code==1 && res.data!=null){
          data.fileAmount = res.data.length
          this.$set(this.kpi.data, index, data)
        }
      }) 
    }
  },
  watch: {
    fileList: function (newQuestion, oldQuestion) {
      newQuestion.forEach((item) => {
        var newIndex = this.fileQueryList.findIndex((item2) => item2.id === item.id)
        if (newIndex == -1) {
          this.fileQueryList.push(item)
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
.dailyTask {
  height: 100%;
  font-size: 14px;
  .navigator {
    min-height: 100%;
    padding: 27px 125px 50px;
    background-color: #f5f5f5;
  }
}
.baseinfo {
  background-color: #fff;
  border: 1px solid #eaeaea;
  padding: 30px;
  margin-top: 20px;
  .btn-box {
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }
}
.info-title {
  font-size: 16px;
  font-weight: bold;
  position: relative;
  padding-left: 14px;
  color: #333333;
  margin-bottom: 14px;
  &:before {
    content: '';
    position: absolute;
    display: block;

    height: 70%;
    top: 15%;
    width: 3px;
    left: 0;
    background-color: #47a4fa;
  }
  /deep/ .ant-btn {
    margin-left: 10px;
    height: 30px;
    line-height: 30px;
  }
}
/deep/ .el-upload__input {
  display: none !important;
}
/deep/ .ant-calendar-picker {
  width: 100%;
}
/deep/ .rowClass {
  // background-color: #e6f7ff;
  background-color: #e6f7ff;
  &:hover:not(.ant-table-expanded-row):not(.ant-table-row-selected) > td {
    background-color: #cae9fb;
  }
}
/deep/ .upload-demo {
  display: inline-block;
  margin-left: 17px;
}

/deep/ #process-container {
  width: auto !important;
}

/deep/ .ant-modal-header{
  border-radius: 15px 15px 0 0;
  background-image: linear-gradient(90deg, #15b1ff 0%,#1158c9 100%);
}
/deep/ .ant-modal-content{
  border-radius: 15px;
}
/deep/ .ant-modal-title,/deep/ .ant-modal-footer{
  text-align: center;
}
/deep/ .ant-modal-title{
  color: #fff;
}

@media (max-width: 1080px) {
  .dailyTask .navigator {
    padding: 27px 30px 50px !important;
  }
}
</style>